using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using Voodoo.Sauce.Common.Utils;
using Voodoo.Sauce.Core;
using Voodoo.Sauce.Internal.Extension;
using Voodoo.Sauce.Privacy;

namespace Voodoo.Sauce.Internal.Analytics
{
	internal class AdnAnalyticsProvider : IAnalyticsProvider
	{
		private const string TAG = "AdnAnalyticsProvider";

		private readonly DateTime _startTime = DateTime.Now;

		private bool _isInitialized;

		private string _unityVersion;

		private string _vsVersion;

		private string _firstAppLaunchDate;

		private int _appOpenCountSinceInstall;

		private string _vanUserId;

		private string _vanImpressionId;

		private string _vanFsImpressionId;

		private string _vanRvImpressionId;

		private string _appStoreId;

		private bool _isRvSkipped;

		private int _playTime;

		private int _loadRequestCount;

		private int _gameCount;

		private int _gameWonCount;

		private AdClick _adClick;

		private AdRevenue _totalRevenue;

		private double? _adRevenue;

		private PerfMetrics _perfMetrics;

		private AdSessionQueue _adSessions;

		private PrivacyCore _privacy;

		public void Instantiate(string mediation)
		{
		}

		public void Initialize(PrivacyCore.GdprConsent consent, bool isChinaBuild)
		{
			try
			{
				InitSessionInfo();
				SendSdkExtrasParameters();
			}
			catch (Exception ex)
			{
				VoodooLog.LogError(Module.ADS, "AdnAnalyticsProvider", "AdnAnalyticsProvider initialization error: " + ex.Message);
			}
		}

		private void OnSdkInitialized()
		{
			try
			{
				if (!_isInitialized)
				{
					_isInitialized = true;
					RegisterEvents();
				}
			}
			catch (Exception ex)
			{
				VoodooLog.LogError(Module.ADS, "AdnAnalyticsProvider", "AdnAnalyticsProvider initialization error: " + ex.Message);
			}
		}

		private void InitSessionInfo()
		{
			IAnalyticStorage instance = AnalyticsStorageHelper.Instance;
			_privacy = VoodooSauceCore.GetPrivacy();
			_totalRevenue = new AdRevenue();
			_adClick = new AdClick();
			_perfMetrics = new PerfMetrics();
			_adSessions = new AdSessionQueue();
			_firstAppLaunchDate = instance.GetFirstAppLaunchDate()?.ToIsoFormat();
			_appOpenCountSinceInstall = instance.GetAppLaunchCount();
			_unityVersion = Application.unityVersion;
			_vsVersion = VoodooConfig.Version();
			_vanUserId = AnalyticsUserIdHelper.GetUserId();
			if (PlatformUtils.UNITY_IOS)
			{
				_appStoreId = VoodooSettings.Load().AppleStoreId;
			}
		}

		private void RegisterEvents()
		{
		}

		private void OnGameFinished(GameFinishedParameters parameters)
		{
			_gameCount++;
			if (parameters.status)
			{
				_gameWonCount++;
			}
			_playTime += parameters.gameDuration / 1000;
		}

		private void OnImpressionTrackedEvent(ImpressionAnalyticsInfo info)
		{
			_adRevenue = info.Revenue;
			ImpressionAdUnitFormat? adUnitFormat = info.AdUnitFormat;
			if (!adUnitFormat.HasValue)
			{
				return;
			}
			switch (adUnitFormat.GetValueOrDefault())
			{
			case ImpressionAdUnitFormat.RewardedVideo:
				if (info.Revenue.HasValue)
				{
					_totalRevenue.RvRevenue += info.Revenue.Value;
				}
				break;
			case ImpressionAdUnitFormat.Interstitial:
				if (info.Revenue.HasValue)
				{
					_totalRevenue.FsRevenue += info.Revenue.Value;
				}
				break;
			}
		}

		private void OnInterstitialClickedEvent(AdClickEventAnalyticsInfo info)
		{
			_adClick.IsFsClicked = true;
		}

		private void OnShowInterstitialEvent(AdShownEventAnalyticsInfo info)
		{
			_adClick.IsFsClicked = false;
		}

		private void OnInterstitialDismissedEvent(AdClosedEventAnalyticsInfo info)
		{
			_adSessions.UpdateAdSessions("fs", info, _adRevenue, _adClick.IsFsClicked, isSkipped: false);
		}

		private void OnRewardedVideoClickedEvent(AdClickEventAnalyticsInfo info)
		{
			_adClick.IsRvClicked = true;
		}

		private void OnShowRewardedVideoEvent(AdShownEventAnalyticsInfo info)
		{
			_adClick.IsRvClicked = false;
			_isRvSkipped = false;
		}

		private void OnRewardedVideoClosedEvent(AdClosedEventAnalyticsInfo info)
		{
			_isRvSkipped = (!info.AdReward) ?? true;
			_adSessions.UpdateAdSessions("rv", info, _adRevenue, _adClick.IsRvClicked, _isRvSkipped);
		}

		private void OnInterstitialLoadRequestEvent(AdAnalyticsInfo info)
		{
			_vanFsImpressionId = info.ImpressionId;
			OnLoadRequestEvent(info);
		}

		private void OnRewardedLoadRequestEvent(AdAnalyticsInfo info)
		{
			_vanRvImpressionId = info.ImpressionId;
			OnLoadRequestEvent(info);
		}

		private void OnLoadRequestEvent(AdAnalyticsInfo info)
		{
			_loadRequestCount++;
			_vanImpressionId = info.ImpressionId;
			SendSdkExtrasParameters();
		}

		private void TrackPerformanceMetrics(PerformanceMetricsAnalyticsInfo metrics)
		{
			_perfMetrics.BadFrames = metrics.BadFrames;
			_perfMetrics.TerribleFrames = metrics.TerribleFrames;
		}

		private void SendSdkExtrasParameters()
		{
			try
			{
				SessionInfo sessionInfo = AnalyticsSessionManager.Instance().SessionInfo;
				IAnalyticStorage instance = AnalyticsStorageHelper.Instance;
				Dictionary<string, object> dictionary = new Dictionary<string, object>();
				dictionary.AddIfNotNull("unity_version", _unityVersion);
				dictionary.AddIfNotNull("vsauce_version", _vsVersion);
				dictionary.AddIfNotNull("session_id", sessionInfo.id);
				dictionary.AddIfNotNull("install_date", _firstAppLaunchDate);
				dictionary.AddIfNotNull("app_open_count_since_install", _appOpenCountSinceInstall);
				dictionary.AddIfNotNull("session_count_since_install", sessionInfo.count);
				dictionary.AddIfNotNull("game_count_since_install", instance.GetGameCount());
				dictionary.AddIfNotNull("fs_count_since_install", instance.GetShowInterstitialCount());
				dictionary.AddIfNotNull("rv_count_since_install", instance.GetShowRewardedVideoCount());
				dictionary.AddIfNotNull("van_user_id", _vanUserId);
				dictionary.AddIfNotNull("van_impression_id", _vanImpressionId);
				dictionary.AddIfNotNull("van_fs_impression_id", _vanFsImpressionId);
				dictionary.AddIfNotNull("van_rv_impression_id", _vanRvImpressionId);
				dictionary.AddIfNotNull("has_skip_prior_rv", _isRvSkipped ? 1 : 0);
				dictionary.AddIfNotNull("play_time", _playTime);
				dictionary.AddIfNotNull("total_time", TimeSinceStartup());
				dictionary.AddIfNotNull("rev_gen", _totalRevenue.ToDictionary());
				dictionary.AddIfNotNull("count_req", _loadRequestCount);
				dictionary.AddIfNotNull("game_count", _gameCount);
				dictionary.AddIfNotNull("perf_metrics", _perfMetrics.ToDictionary());
				dictionary.AddIfNotNull("game_count_success", _gameWonCount);
				dictionary.AddIfNotNull("has_last_click", _adClick.ToDictionary());
				dictionary.AddIfNotNull("last_x_session_desc", _adSessions.LatestSessionsDictionaryList());
				dictionary.AddIfNotNull("first_x_session_desc", _adSessions.FirstSessionsDictionaryList());
				dictionary.AddIfNotNull("appstore_id", _appStoreId);
				dictionary.AddIfNotNull("ads_consent_given", _privacy.HasAdsConsent() ? 1 : 0);
				dictionary.AddIfNotNull("idfa_authorization_status", _privacy.GetAuthorizationStatus().ToString());
				JsonConvert.SerializeObject(dictionary);
			}
			catch (Exception ex)
			{
				VoodooLog.LogError(Module.ADS, "AdnAnalyticsProvider", "AdnAnalyticsProvider SetExtrasParameters error: " + ex.Message);
			}
		}

		private int TimeSinceStartup()
		{
			double totalSeconds = (DateTime.Now - _startTime).TotalSeconds;
			if (totalSeconds > 0.0)
			{
				return (int)totalSeconds;
			}
			return 0;
		}
	}
}
